package com.life.ai.server.modules.system.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.util.IdUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.life.ai.server.common.constants.CacheConstants;
import com.life.ai.server.common.domain.R;
import com.life.ai.server.common.utils.RedisUtils;
import com.life.ai.server.framework.config.properties.SystemProperties;
import com.life.ai.server.modules.system.model.dto.LoginParamDTO;
import com.life.ai.server.modules.system.model.vo.CaptchaImageVO;
import com.life.ai.server.modules.system.model.vo.SysUserInfoVO;
import com.life.ai.server.modules.system.service.SysLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * SysAuthController
 *
 * @author kylewka
 * @since 2024/6/14
 */
@Api(tags = "授权认证-接口列表")
@RestController
@RequestMapping("/system/auth")
public class SysAuthController {

    @Resource
    private SysLoginService loginService;

    @SaIgnore
    @ApiOperationSupport(order = 1)
    @ApiOperation("登录验证码")
    @GetMapping("/captchaImage")
    public R<CaptchaImageVO> getCode() {
        CaptchaImageVO captchaImageVo = new CaptchaImageVO();
        boolean captchaEnabled = SystemProperties.enableLoginCaptcha;
        captchaImageVo.setCaptchaEnabled(captchaEnabled);
        if (!captchaEnabled) {
            return R.ok(captchaImageVo);
        }
        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        // 设置验证码尺寸
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(100, 35,4,0);
        captcha.createCode();

        RedisUtils.set(verifyKey, captcha.getCode(), 300L);
        captchaImageVo.setUuid(uuid);
        captchaImageVo.setImg(captcha.getImageBase64());
        return R.ok(captchaImageVo);
    }

    @SaIgnore
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "账号密码登录")
    @PostMapping("/login")
    public R<SaTokenInfo> login(@Validated @RequestBody LoginParamDTO loginParam) {
        SaTokenInfo tokenInfo = loginService.login(loginParam);
        return R.ok(tokenInfo);
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public R<Void> logout() {
        loginService.logout();
        return R.ok();
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/info")
    public R<SysUserInfoVO> currentUserInfo() {
        SysUserInfoVO userInfoVO = loginService.currentUserInfo();
        return R.ok(userInfoVO);
    }

}
